package com.rc.saas.tenant.service.operator;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.common.mq.MqProducer;
import com.rc.saas.tenant.common.utils.MD5Utils;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.mapper.operator.RcOperatorMapper;
import com.rc.saas.tenant.model.member.MemberInfo;
import com.rc.saas.tenant.model.member.RcMemberFlag;
import com.rc.saas.tenant.model.member.RcMemberFlagExample;
import com.rc.saas.tenant.model.operator.RcOperator;
import com.rc.saas.tenant.model.operator.RcOperatorExample;
import com.rc.saas.tenant.model.tenant.TenantRole;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.search.account.WithdrawMagSearch;
import com.rc.saas.tenant.search.operator.OperatorSearch;
import com.rc.saas.tenant.service.member.MemberInfoService;
import com.rc.saas.tenant.service.member.RcMemberFlagService;
import com.rc.saas.tenant.service.tenant.TenantRoleService;
import com.rc.saas.tenant.service.tenant.TenantUserService;
import com.rc.saas.tenant.vo.account.WithDrawManagerDetailVo;
import com.rc.saas.tenant.vo.account.WithDrawManagerVo;
import com.rc.saas.tenant.vo.elec.ElecCountVo;
import com.rc.saas.tenant.vo.operator.RcOperatorVo;
import com.rc.saas.tenant.vo.tenant.TenantUserRoleVo;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by sven on 2019/11/14
 */
@Service
public class RcOperatorServiceImpl implements RcOperatorService {

    private static Logger logger = LogManager.getLogger(RcOperatorServiceImpl.class);

    @Autowired
    private RcOperatorMapper rcOperatorMapper;

    @Autowired
    private RcMemberFlagService memberFlagService;

    @Autowired
    private TenantUserService tenantUserService;

    @Autowired
    private RestTemplate hcRestTemplate;

    @Autowired
    private MqProducer mqProducer;

    @Autowired
    private MemberInfoService memberInfoService;

    @Autowired
    private RcMemberFlagService rcMemberFlagService;

    @Autowired
    private TenantRoleService tenantRoleService;

    @Override
    public RcOperatorMapper getMapper() {
        return rcOperatorMapper;
    }

    @Override
    public List<RcOperator> loadOperator(String loginName) {
        OperatorSearch operatorSearch = new OperatorSearch();
        operatorSearch.setLoginName(loginName);
        TenantUserRoleVo userRoleVo = tenantRoleService.getLonginRole(operatorSearch.getLoginName());
        if (userRoleVo!=null){
            operatorSearch.setRoleType(userRoleVo.getRoleType());
            operatorSearch.setDataAuth(userRoleVo.getDataAuth());
            switch (userRoleVo.getRoleType()){
                case "1"://自定义用户
                    operatorSearch.setOperatorIds(
                            StringUtils.isNotBlank(userRoleVo.getOperatorIds())?
                                    Arrays.asList(userRoleVo.getOperatorIds().split(","))
                                    :new ArrayList<String>());
                    operatorSearch.setEnterpriseIds(
                            StringUtils.isNotBlank(userRoleVo.getEnterpriseIds())?
                                    Arrays.asList(userRoleVo.getEnterpriseIds().split(","))
                                    :new ArrayList<String>());
                    break;
                case "2"://加盟商用户
                    operatorSearch.setOperatorIds(StringUtils.isNotBlank(userRoleVo.getOperatorIds())?
                            Arrays.asList(userRoleVo.getOperatorIds().split(","))
                            :new ArrayList<String>());
                    break;
                case "3"://企业用户
                    operatorSearch.setEnterpriseIds(StringUtils.isNotBlank(userRoleVo.getEnterpriseIds())?
                            Arrays.asList(userRoleVo.getEnterpriseIds().split(","))
                            :new ArrayList<String>());
                    break;
            }
        }
        List<RcOperator> rcLabels = rcOperatorMapper.loadOperator(operatorSearch);
        return rcLabels;
    }

    @Override
    public List<RcOperator> selectOperators(String tenantCode) {
        return rcOperatorMapper.selectOperators(tenantCode);
    }

    @Override
    public PageInfo listPageOperator(String operatorName, Integer pageNo, Integer pageSize) {
        PageHelper.startPage(pageNo, pageSize);
        List<RcOperatorVo> list = rcOperatorMapper.listOperator(operatorName);
        return new PageInfo(list);
    }

    @Override
    public void updateOperatorApplyForAudit(Long id, Long memberId, String status, String remark) {
        RcOperator operator = rcOperatorMapper.selectByPrimaryKey(id);
        operator.setApplyStatus(status);
        if ("1".equals(status)) {
            TenantUser user = tenantUserService.selectByMobile(operator.getPhone());
            if (user == null) {
                user = new TenantUser();
                user.setEnterpriseId(operator.getEnterpriseId());
                user.setUserType("1");
                user.setLoginName(operator.getPhone());
                String saltPassword = MD5Utils.encrypt(user.getLoginName(), user.getLoginName());
                user.setPassword(saltPassword);
                user.setMobile(operator.getPhone());
                user.setRealName(operator.getContactName());
                tenantUserService.insertSelective(user);
            }

            if (operator.getMemberId() == null || operator.getMemberId() == 0) {
                operator.setMemberId(memberId);
            }

            if (operator.getMemberId() != null && operator.getEnterpriseId() != null) {
                memberFlagService.addOperator(id, operator.getMemberId(), operator.getEnterpriseId());
            }

        }
        operator.setRemark(remark);
        rcOperatorMapper.updateByPrimaryKeySelective(operator);
    }

    @Override
    public TResponse saveOperator(String tenantCode, RcOperator operator) {
        if (operator.getOperatorId() == null) {
            //String mobile = RandomValueUtil.getTel();
            String mobile = operator.getPhone();

            Pattern VerifyPhoneNumber = Pattern.compile("0?(13|14|15|17|18|19)[0-9]{9}");
            Matcher matcher = VerifyPhoneNumber.matcher(mobile);
            if (!matcher.matches()) {
                return TResponse.FAIL("请输入正确的手机号");
            }

            MemberInfo memberInfo = memberInfoService.selectMemberByMobile(tenantCode, mobile);
            if (memberInfo != null) {
                return TResponse.FAIL("此手机号已被注册");
            }

            Long  operatorId = rcOperatorMapper.insertReturnId(operator);
            //缺少插入tenant_role表 加盟商Id,tenant_user 加盟商Id
        } else {
            rcOperatorMapper.updateByPrimaryKeySelective(operator);
        }
        return TResponse.SUCCESS();
    }

    @Override
    public void deleteOperator(Long id) {

        RcOperator operator = rcOperatorMapper.selectByPrimaryKey(id);
        if ("1".equals(operator.getApplyStatus())
                && "1".equals(operator.getStatus())
                && operator.getMemberId() != null) {
            memberFlagService.delOperator(operator.getMemberId());
        }
        rcOperatorMapper.deleteByPrimaryKey(id);

    }

    @Override
    public RcOperator selectOperatorApplyByOperator(String operator) {
        return rcOperatorMapper.selectOperatorApplyByOperator(operator);
    }

    @Override
    public PageInfo<WithDrawManagerVo> listWithdrawManagerVo(WithdrawMagSearch withdrawMagSearch) {
        PageHelper.startPage(withdrawMagSearch.getOffset(), withdrawMagSearch.getLimit());
        List<WithDrawManagerVo> withDrawManagerVos = rcOperatorMapper.listWithdrawManagerVo(withdrawMagSearch.getMemberIdAndNickname(), withdrawMagSearch.getMemberType());

        List<WithDrawManagerVo> result = new ArrayList<>();

        for (WithDrawManagerVo withDrawManagerVo : withDrawManagerVos) {
            if (withdrawMagSearch.getMemberType() == null || withdrawMagSearch.getMemberType().equals("")) {
                return new PageInfo(withDrawManagerVos);
            } else if ("加盟商".equals(withDrawManagerVo.getMemberType()) && "0".equals(withdrawMagSearch.getMemberType())) {
                result.add(withDrawManagerVo);
            } else if ("渠道商".equals(withDrawManagerVo.getMemberType()) && "1".equals(withdrawMagSearch.getMemberType())) {
                result.add(withDrawManagerVo);
            }
        }
        return new PageInfo(result);
    }

    @Override
    public PageInfo<WithDrawManagerDetailVo> listWithdrawManagerDetailVo(WithdrawMagSearch withdrawMagSearch) {
        PageHelper.startPage(withdrawMagSearch.getOffset(), withdrawMagSearch.getLimit());
        List<WithDrawManagerDetailVo> result = rcOperatorMapper.listWithdrawManagerDetailVo(withdrawMagSearch);
        return new PageInfo(result);
    }

    @Override
    public TResponse addMember(String mobile) {

        //角色对象
        TenantRole tenantRole = tenantRoleService.selectByRoleType("2");

        RcOperator rcOperator = this.selectMobile(mobile);

        TenantUser user = tenantUserService.selectByMobile(mobile);
        if (user == null) {
            user = new TenantUser();
            user.setEnterpriseId(rcOperator.getEnterpriseId());
            user.setUserType("2");
            user.setLoginName(rcOperator.getPhone());
            String saltPassword = MD5Utils.encrypt(user.getLoginName(), user.getLoginName());
            user.setPassword(saltPassword);
            user.setMobile(rcOperator.getPhone());
            user.setRealName(rcOperator.getContactName());
            user.setTenantRoleId(tenantRole.getTenantRoleId());
            user.setOperatorId(rcOperator.getOperatorId());
            tenantUserService.insertSelective(user);
        } else {
            return TResponse.FAIL("审核失败,手机号已存在");
        }

        String url = "https://charge.ruishangkj.com/rc-mini/user/open/webLoginByAuthCode?authCode=56789&mobile=";
        url = url + mobile;
        //创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> requestEntity = new HttpEntity<String>(headers);
        //返回字符串
        ResponseEntity<String> response = hcRestTemplate.postForEntity(url, requestEntity, String.class);
        String body = response.getBody();
        HashMap map = JSON.parseObject(body, HashMap.class);
        if ((int) map.get("status") == 200) {
            JSONObject jsonObject = (JSONObject) map.get("data");
            Long memberId = Integer.toUnsignedLong((Integer) jsonObject.get("memberId"));


            if (memberId == null) {
                return TResponse.FAIL();
            }
            logger.info("生成会员成功id:{}", memberId);
            rcOperator.setMemberId(memberId);
            rcOperatorMapper.updateByPrimaryKeySelective(rcOperator);

            //生成会员标识
            RcMemberFlagExample rcMemberFlagExample = new RcMemberFlagExample();
            rcMemberFlagExample.createCriteria().andMemberIdEqualTo(memberId);
            RcMemberFlag rcMemberFlag = new RcMemberFlag();
            rcMemberFlag.setIsOperator("1");
            rcMemberFlagService.updateByExampleSelective(rcMemberFlag, rcMemberFlagExample);
        }
        return null;
    }

    @Override
    public ElecCountVo loadElecCount(Long operatorId) {
        return rcOperatorMapper.loadElecCount(operatorId);
    }

    @Override
    public RcOperator selectMobile(String mobile) {
        RcOperatorExample example = new RcOperatorExample();
        example.createCriteria().andPhoneEqualTo(mobile);
        List<RcOperator> rcOperators = rcOperatorMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(rcOperators)) {
            return rcOperators.get(0);
        }
        return null;
    }
}
